package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

var filepath string

//文件接收器
func main() {
	//获取socket
	listener, err := net.Listen("tcp", "localhost:8001")
	if err != nil {
		fmt.Println("net.Listen err = ", err)
		return
	}
	//确保关闭流
	defer listener.Close()
	//接收器启动成功
	fmt.Println("接收器启动成功.........")
	//等待用户输入文件保存的目录
	fmt.Println("请输入文件需要保存路径: ")
	fmt.Scan(&filepath)
	//阻塞监听用户连接
	conn, err1 := listener.Accept()
	if err1 != nil {
		fmt.Println("net.Listen err = ", err1)
		return
	}
	defer conn.Close()
	var buf = make([]byte, 1024)
	var n int
	if n, err = conn.Read(buf); err != nil {
		fmt.Println("conn.Read err = ", err)
		return
	}
	fileName := string(buf[:n])
	//获取文件成功后 向客户端返回"ok"
	_, err = conn.Write([]byte("ok"))
	if err != nil {
		fmt.Println("conn.Write err = ", err)
	}
	//接收文件
	RecvFile(fileName, conn)

}

//该函数用与接收文件内容
func RecvFile(fileName string, conn net.Conn) {
	//新建文件
	fileInput, err := os.Create(filepath + "\\" + fileName)
	if err != nil {
		fmt.Println("os.Create err = ", err)
		return
	}
	//确保函数结束时 流能被正确关闭
	defer fileInput.Close()
	//创建一个切片缓冲
	var buf = make([]byte, 2048)
	var n int
	for {
		n, err = conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				fmt.Println("文件接收完毕")
				return
			} else {
				fmt.Println("conn.Read err = ", err)
				return
			}
		}
		_, err = fileInput.WriteString(string(buf[:n]))
		if err != nil {
			fmt.Println("fileInput.WriteString err = ", err)
		}
	}

}
